package com.hundun.hddeal.controller;
import com.github.pagehelper.PageInfo;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.hundun.hddeal.dao.AdUserMapper;
import com.hundun.hddeal.dao.GzhMapper;
import com.hundun.hddeal.dao.MtUserMapper;
import com.hundun.hddeal.entity.Gzh;
import com.hundun.hddeal.entity.GzhBody;
import com.hundun.hddeal.entity.MtUser;
import com.hundun.hddeal.entity.User;
import com.hundun.hddeal.response.Result;
import com.hundun.hddeal.response.ResultUtil;
import com.hundun.hddeal.service.lmpl.GzhServiceImpl;
import com.hundun.hddeal.service.lmpl.GzhTypeServiceImpl;
import com.hundun.hddeal.service.lmpl.MtUserServiceImpl;
import com.hundun.hddeal.util.*;
import com.hundun.hddeal.vo.GzhVo;
import com.hundun.hddeal.vo.MtUserVo;
import com.hundun.hddeal.vo.RequestPageBean;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.*;
import static org.assertj.core.util.DateUtil.now;


/**
 * 媒体用户
 * @author 谢
 */
@CrossOrigin
@RestController
@RequestMapping("mt")
@Slf4j
public class MtUserController {

    @Autowired
    MtUserServiceImpl mtUserService;
    @Autowired
    GzhServiceImpl gzhService;
    @Autowired
    GzhMapper gzhMapper;
    @Autowired
    MtUserMapper mtUserMapper;
    @Autowired
    GzhTypeServiceImpl gzhTypeService;
    @Autowired
    AdUserMapper adUserMapper;


    /**
     * 登陆
     * @param mtUser
     * @return
     */
    @PostMapping("login")
    public Result login(@RequestBody MtUser mtUser) {
        return mtUserService.selectByMtUserId(mtUser);
    }


    /**
     * 短信验证登陆
     */
    @PostMapping("noteLogin")
    public Result noteLogin(@RequestBody MtUserVo mtUserVo){
        return mtUserService.noteLogin(mtUserVo.getMtPhone(),mtUserVo.getNote());
    }



    /**
     * 注册
     * @param mtUser
     * @return
     */
    @PostMapping("register")
    public Result register(@RequestBody MtUser mtUser) {
        return mtUserService.register(mtUser);
    }

    /**
     * 更新用户信息
     * @param mtUservo
     * @return
     */
    @PostMapping("updateMt")
    public Result update(@RequestBody MtUserVo mtUservo){
        String mtUserId = TokenUtilT.getTokenById(mtUservo.getMtUserToken());
        MtUser mtUser1=mtUserService.selectByMtUserId(mtUserId);
        if("".equals(mtUservo.getMtPhone())) {
            return ResultUtil.error("请填写手机号码");
        }
        if("".equals(mtUservo.getMtCompany())) {
            return ResultUtil.error("请填写公司名称");
        }
        mtUser1.setUpdateDate(now());
        mtUser1.setMtId(mtUserId);
        mtUser1.setMtName(mtUservo.getMtName());
        MtUser mtUser =mtUserMapper.selectPhone(mtUservo.getMtPhone());
        if(mtUser!=null){
            if(mtUser.getMtPhone().equals(mtUservo.getMtPhone())&& !mtUser1.getMtPhone().equals(mtUservo.getMtPhone())){
                return ResultUtil.error("该手机号码已被注册");
            }
        }
        mtUser1.setMtPhone(mtUservo.getMtPhone());

        mtUser1.setMtQq(mtUservo.getMtQq());
        mtUser1.setMtWx(mtUservo.getMtWx());
        mtUser1.setMtEmail(mtUservo.getMtEmail());
        mtUser1.setPhoneNum(mtUservo.getPhoneNum());
        mtUser1.setMtCompany(mtUservo.getMtCompany());
        if(mtUservo.getNewPwd()!=null){
            if(!MD5Util.getSaltverifyMD5(mtUservo.getMtPwd(),mtUser1.getMtPwd())){
                return ResultUtil.error("原登陆密码不对！");
            }
            mtUser1.setMtPwd(MD5Util.getSaltMD5(mtUservo.getNewPwd()));
        }


        if(mtUservo.getNewtakePwd()!=null){
            if(!MD5Util.getSaltverifyMD5(mtUservo.getTakePwd(),mtUser1.getTakePwd())){
                return ResultUtil.error("原提现密码不对！");
            }
            mtUser1.setTakePwd(MD5Util.getSaltMD5(mtUservo.getNewtakePwd()));
        }
        return mtUserService.updateByPrimaryKeySelective(mtUser1);
    }

    /**
     * 增加公众号
     * @param
     * @param
     * @return
     */
    @PostMapping("addgzh")
    public Result addGzh(@RequestBody GzhVo gzhVo){
        String mtUserId = TokenUtilT.getTokenById(gzhVo.getMtUserToken());
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        Gzh g= gzhMapper.selectByGhId(gzhVo.getGhId());
        if(g!=null){
            return ResultUtil.error("添加失败！该账户已存在！");
        }
        if(mtUserId!=null){
            Gzh gzh = new Gzh();
            gzh.setGzhId(mtUser.getId());
            gzh.setMtName(mtUser.getMtId());
            gzh.setGzhName(gzhVo.getGzhName());
            gzh.setGhId(gzhVo.getGhId());
            int count= gzhMapper.selectGzhData(gzhVo.getGhId());
            if(count==0){
                gzhMapper.setGzhData(gzhVo.getGhId());
            }
            gzh.setUserName(mtUser.getUserName());
            gzh.setFz(mtUser.getFz());
            gzh.setGzhUrl(gzhVo.getGzhUrl());
            gzh.setGzhLogo(gzhVo.getGzhLogo());
            gzh.setGzhCode(gzhVo.getGzhCode());
            gzh.setGzhFans(gzhVo.getGzhFans());
            gzh.setFansPic(gzhVo.getFansPic());
            gzh.setGzhType(gzhVo.getGzhType());
            gzh.setWxOriginId(gzhVo.getWxOriginId());

            //base64编码
            Base64.Encoder encoder = Base64.getEncoder();
            byte[] textByte = gzhVo.getGzhIntro().getBytes(StandardCharsets.UTF_8);
            String encodedText = encoder.encodeToString(textByte);
            gzh.setGzhIntro(encodedText);
            gzh.setGzhAge(gzhVo.getGzhAge());
            gzh.setTypeName(gzhVo.getTypeName());
            gzh.setPriceFirst(gzhVo.getPriceFirst());
            gzh.setPriceSecond(gzhVo.getPriceSecond());
            gzh.setPriceOne(gzhVo.getPriceOne());
            gzh.setCityOne(gzhVo.getCityOne());
            gzh.setGzhSex(gzhVo.getGzhSex());
            gzh.setCreateDate(now());
            if(gzhVo.getPriceFirst()!=null){
                if(gzhVo.getPriceFirst()<=200) {
                    //价钱状态
                    gzh.setGzhPrice(1);
                }else  if(gzhVo.getPriceFirst()<=500&&gzhVo.getPriceFirst()>200) {
                    gzh.setGzhPrice(2);
                }else  if (gzhVo.getPriceFirst()<=1000&&gzhVo.getPriceFirst()>500){
                    gzh.setGzhPrice(3);
                }else   if (gzhVo.getPriceFirst()<=3000&&gzhVo.getPriceFirst()>1000){
                    gzh.setGzhPrice(4);
                }else  if (gzhVo.getPriceFirst()>3000){
                    gzh.setGzhPrice(5);
                }
            }

            double fans =(double)gzh.getGzhFans()/10000;
            if(fans<=1) {
                gzh.setFansType(1);
            }else if(fans<=5&&fans>1) {
                gzh.setFansType(2);
            }else if (fans<=10&&fans>5){
                gzh.setFansType(3);
            }else if (fans<=20&&fans>10){
                gzh.setFansType(4);
            }else if (gzhVo.getGzhFans()<=40&&fans>20){
                gzh.setFansType(5);
            }else  if (gzhVo.getGzhFans()<=80&&fans>40){
                gzh.setFansType(6);
            }else if (gzhVo.getGzhFans()<=120&&fans>80){
                gzh.setFansType(7);
            }else if (fans<=200&&fans>120){
                gzh.setFansType(8);
            }else if (fans>200){
                gzh.setFansType(9);
            }

            return gzhService.addGzh(gzh);
        }
        return ResultUtil.error("无token，重新登陆");
    }

    /**
     * 批量上传公众号
     * @param token
     * @param file
     * @return
     */
    @PostMapping("moregzh")
    public Result moreGzh(@RequestParam("mtUserToken")String token,@RequestParam("file") MultipartFile file){
        String mtUserId = TokenUtilT.getTokenById(token);
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if(mtUser!=null) {
            try{
                List<Gzh> gzhs = EasyPoiUtil.importExcel(file,0,1,Gzh.class);
                //迭代器删除空的对象
                gzhs.removeIf(gzh -> gzh.getGzhName() == null && gzh.getGhId() == null && gzh.getGzhPwd() == null);

                HashSet<String> hashSet = new HashSet<>();
                for(Gzh gzh:gzhs){
                    hashSet.add(gzh.getGhId());
                }
                if(gzhs.size()>hashSet.size()){
                    return ResultUtil.error("有重复的原始Id,请仔细查找修改!");
                }

                log.info("导入数据:"+gzhs.size());
                String[] arr=new String[gzhs.size()];
                for(int i=0;i<gzhs.size();i++){
                    arr[i]=gzhs.get(i).getGhId();
                    if("不限".equals(gzhs.get(i).getAge())){
                        gzhs.get(i).setGzhAge(0);
                    }else if("少年".equals(gzhs.get(i).getAge())){
                        gzhs.get(i).setGzhAge(1);
                    }else if("青年".equals(gzhs.get(i).getAge())){
                        gzhs.get(i).setGzhAge(2);
                    }else if("中年".equals(gzhs.get(i).getAge())){
                        gzhs.get(i).setGzhAge(3);
                    }else if("老年".equals(gzhs.get(i).getAge())){
                        gzhs.get(i).setGzhAge(4);
                    }
                }
                //查询数据库是否有存在的公众号
                List<Gzh> gzhCopy=gzhMapper.selectByGhIds(arr);
                StringBuffer buf = new StringBuffer();
                if(gzhCopy.size()!=0){
                    for(Gzh gzh:gzhCopy){
                        buf.append(gzh.getGzhName()).append(",");
                    }
                    return ResultUtil.error("公众号名为："+buf.toString()+"已存在");
                }


                ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();
                int size = gzhs.size();
                ExecutorService fixedThreadPool = new ThreadPoolExecutor(size,size,0L,TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024),namedThreadFactory);
                for(Gzh gzh:gzhs){
                    fixedThreadPool.execute(() -> {
                        int count= gzhMapper.selectGzhData(gzh.getGhId());
                        if(count==0){
                            gzhMapper.setGzhData(gzh.getGhId());
                        }
                        gzh.setGzhId(mtUser.getId());
                        gzh.setMtName(mtUser.getMtId());
                        gzh.setUserName(mtUser.getUserName());
                        gzh.setFz(mtUser.getFz());
                        gzhMapper.insertSelective(gzh);
                        OkHttpUtil okHttpUtil =new OkHttpUtil();
                        Map<String,Object> map =new HashMap<>(1);
                        map.put("gh_detail",gzh.getGhId());
                        try {
                            //调用爬虫接口
                            Response response = okHttpUtil.get(map,"https://www.hundun4a.com:8899/get_detail");
                            if (response.body() != null) {
                                log.info(response.body().string());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //okHttpUtil.get(map,"http://192.168.1.190:8899/get_detail"); //调用爬虫接口 https://www.hundun4a.com:8899/get_detail
                    });

                }
                fixedThreadPool.shutdown();
                return ResultUtil.success();
            }catch (Exception e){
                e.printStackTrace();
                String message=e.getMessage();
                if(message==null){
                    return ResultUtil.error("未知错误");
                }
                return ResultUtil.error(e.getMessage()+",如不是空则请清除空白的内容的列");
            }

        }
        return ResultUtil.error();
    }

    /**
     * 更新公众号
     * @param
     * @param
     * @return
     */
    @PostMapping("updateGzh")
    public Result updateGzh(@RequestBody GzhVo gzhVo) {
        String mtUserId = TokenUtilT.getTokenById(gzhVo.getMtUserToken());
        if(mtUserId!=null){
            return gzhService.updateGzh(gzhVo);
        }
        return ResultUtil.error("无token，重新登陆");
    }


    /**
     *获取单个公众号
     * @param gzhVo
     * @return
     */
    @PostMapping("getOneGzh")
    public Result getOneGzh(@RequestBody GzhVo gzhVo){
        String mtUserId = TokenUtilT.getTokenById(gzhVo.getMtUserToken());
        if(mtUserId!=null){
            return gzhService.selectByPrimaryKey(gzhVo.getGhId());
        }
        return ResultUtil.error("无token，重新登陆");
    }



    /**
     * 删除GZH
     * @param
     * @param
     * @return
     */
    @PostMapping("deletegzh")
    public Result deleteGzh(@RequestBody GzhVo gzhVo) {
        String mtUserId = TokenUtilT.getTokenById(gzhVo.getMtUserToken());
        if(mtUserId!=null){
            Gzh gzh = gzhMapper.selectByGhId(gzhVo.getGhId());
            if(gzh.getStatus()==2){
               return ResultUtil.error("该公众号正在接单中，不能删除！");
            }
            return gzhService.deleteGzh(gzh);
        }
        return ResultUtil.error("无token，重新登陆");
    }


    /**
     * 通过状态和用户Id查找公众号接口
     * @param pageBean
     * @return
     */
    @PostMapping("getsh")
    public  Result<PageInfo<GzhBody>> getShGzh(@RequestBody RequestPageBean pageBean){
        String mtId = TokenUtilT.getTokenById(pageBean.mtUserToken);
        if(mtId!=null){
            MtUser mtUser = mtUserService.selectByMtUserId(mtId);
            String cityOne=pageBean.getCityOne();
            Double gzhSex=pageBean.getGzhSex();
            List<String> typeName= new ArrayList<>();
            if(pageBean.getTypeName()!=null){
                String[] split = pageBean.getTypeName().split(",");
                //分割类别添加进集合
                typeName.addAll(Arrays.asList(split));
            }
            if(pageBean.getGzhSex()==null || pageBean.getGzhSex()==0){
                gzhSex=null;
            }
            String unlimited="不限";
            if(pageBean.getTypeName()==null || unlimited.equals(pageBean.getTypeName())){
                typeName=null;
            }
            String nationwide="全国";
            if(pageBean.getCityOne()==null|| nationwide.equals(pageBean.getCityOne())){
                cityOne=null;
            }
            PageInfo<GzhBody> pageInfo = gzhService.selectByMtId(pageBean.getPageNum(), pageBean.getPageSize(),
                    mtUser.getMtId(),pageBean.getStatus(),pageBean.getGzhName(),gzhSex,typeName,cityOne,pageBean.getGzhType(),
                    pageBean.getReadOne(),pageBean.getReadTwo(),pageBean.getFans(),pageBean.getScoreOne(),pageBean.getScoreTwo(),
                    pageBean.getGhId(),pageBean.getAdmin(),pageBean.getFailureCookie());
            return ResultUtil.success(pageInfo);
        }
        return ResultUtil.error("无token");
    }



    /**
     * 初始化个人信息
     * @param
     * @return
     */
    @PostMapping("getmt")
    public Result<MtUser> getMtUserInfo(@RequestBody MtUserVo mtUserVo){
        String mtId = TokenUtilT.getTokenById(mtUserVo.getMtUserToken());
        if (mtId!=null){
            MtUser mtUser = mtUserService.selectByMtUserId(mtId);
            return ResultUtil.success(mtUser);
        }
        return ResultUtil.error("无token");
    }

    /**
     * 更改公众号状态为1：正常
     * @param gzhVo
     * @return
     */
    @PostMapping("change")
    public Result changeState(@RequestBody GzhVo gzhVo) {
        String mtId = TokenUtilT.getTokenById(gzhVo.getMtUserToken());
        MtUser mtUser = mtUserService.selectByMtUserId(mtId);
        Gzh gzh = gzhMapper.selectByGhId(gzhVo.getGhId());
        if(gzh!=null&&gzh.getStatus()!=1&&mtUser!=null){
            gzh.setStatus((byte)1);
            gzhMapper.updateByPrimaryKeySelective(gzh);
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }


    /**
     * 查询用户金额
     * @param map
     * @return
     */
    @PostMapping("getMoney")
    public Result getMoney(@RequestBody Map<String ,String> map){
        String token=map.get("mtUserToken");
        String mtUserId = TokenUtilT.getTokenById(token);
        return mtUserService.findMtUserByMtId(mtUserId);
    }


    /**
     * 注册时判断是否存在用户
     * @param map
     * @return
     */
    @PostMapping("haveMtUser")
    public Result isHaveUser(@RequestBody Map<String ,String> map){
        MtUser mtUser = mtUserMapper.selectByMtUserId(map.get("mtId"));
        if (mtUser != null) {
            return ResultUtil.error("已存在");
        }else {
            return  ResultUtil.success();
        }
    }


    /**
     * 扫描登录注册公众号
     * @param gzhVo
     * @return
     */
    @PostMapping("addCodeGzh")
    public Result addCodeGzh(@RequestBody GzhVo gzhVo) throws NoSuchAlgorithmException {
        String mtUserId = TokenUtilT.getTokenById(gzhVo.getMtUserToken());
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if(mtUser!=null){
            Gzh g= gzhMapper.selectByGhId(gzhVo.getGhId());
            if(g!=null){
                if(g.getGzhPwd()==null){
                    g.setGzhPwd(gzhVo.getGzhPwd());
                    g.setTypeName(gzhVo.getTypeName());
                    gzhMapper.updateByPrimaryKeySelective(g);
                }
            }else {
                Gzh gzh=new Gzh();
                gzh.setTypeName(gzhVo.getTypeName());
                gzh.setGhId(gzhVo.getGhId());
                gzh.setGzhPwd(gzhVo.getGzhPwd());
                gzh.setGzhId(mtUser.getId());
                gzh.setMtName(mtUser.getMtId());
                gzh.setReadOnePrice(gzhVo.getPriceFirst());
                gzh.setReadSecondPrice(gzhVo.getPriceSecond());
                int count= gzhMapper.selectGzhData(gzhVo.getGhId());
                if(count==0){
                    gzhMapper.setGzhData(gzhVo.getGhId());
                }
                gzhService.addGzh(gzh);
            }

            Map<String,String> map =new HashMap<>(2);
            map.put("gzhPwd",MD5Util.MD(gzhVo.getGzhPwd()));
            map.put("ghId",gzhVo.getGhId());
            return ResultUtil.success(map);
        }
        return ResultUtil.error("无token");
    }

    /**
     * 获取公众号类型
     * @param gzhVo
     * @return
     */
    @PostMapping("getGzhType")
    public Result getGzhType(@RequestBody GzhVo gzhVo){
        return gzhTypeService.selectByPrimaryKey(gzhVo.getType());
    }

    /**
     * 获取已上传公众号：100个，合计粉丝：1600.35万
     * @param gzhVo
     * @return
     */
    @PostMapping("getGzhCount")
    public Result getGzhCount(@RequestBody GzhVo gzhVo){
        String mtUserId = TokenUtilT.getTokenById(gzhVo.getMtUserToken());
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if(mtUser!=null){
            return gzhService.getGzhCount(mtUserId);
        }
        return ResultUtil.error("无token");
    }



}
